<template>
    <div class="app-container" ref="app-container">
        <el-table id="elTable" stripe v-tableMove :data="tableDataList" v-if="showTable" v-loading="loading" border fit
            highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange" height="100%"
            @sort-change="handleSortChange" @row-click="handleRowClick"
            :header-cell-style="{ background: '#d6d6d6 !important', color: '#666  !important' }">
            <!-- 是否有多选 -->
            <el-table-column type="selection" width="55" v-if="table_config.isCheckBox || isSelect"
                :selectable="selectable"></el-table-column>
            <!-- 是否需要序号 -->
            <!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->
            <el-table-column label="序号" width="55" align="center">
                <template slot-scope="scope">{{ scope.row.$index >= 0 ? scope.row.$index + 1 : '' }}</template>
            </el-table-column>
            <template v-for="item, index in itemList">
                <el-table-column v-if="item && item['isShow']" :key="item.prop + '_' + index" :prop="item.prop"
                    :label="item.label" :min-width="item.minWidth" :sortable="item.sortable ? true : false"
                    align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.$index >= 0">
                            <!-- 自定义slot 插槽 -->
                            <div v-if="item.slotName">
                                <slot :name=item.slotName :row="scope.row"></slot>
                            </div>
                            <!-- 有状态过滤 -->
                            <span v-else-if="item.filter" :class="item.specialClass && item.specialClass(scope.row)">
                                {{ item.callback && item.callback(scope.row) }}
                            </span>
                            <!-- 图片展示 -->
                            <img v-else-if="item.image" :src="scope.row[item.prop]" style="width:40px; height: 40px">
                            <!-- switch开关 -->
                            <el-switch v-else-if="item.switch" v-model="scope.row[item.prop]" active-text="启用"
                                active-value=1 inactive-value=0 inactive-text="停用"
                                @change="item.callback && item.callback(scope.row)">
                            </el-switch>
                            <!-- 有跳转 -->
                            <router-link v-else-if="item.router"
                                :to="{ path: item.routerPath, query: { name: scope.row[item.prop] } }">
                                {{ scope.row[item.prop] }}
                            </router-link>
                            <!-- 默认展示 -->
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </div>
                    </template>
                </el-table-column>
            </template>

            <!-- 操作列 -->
            <el-table-column :label="table_config.operation.label" :fixed="configFixed.flag"
                :width="table_config.operation.width" align="center" v-if="isShow">
                <template slot-scope="scope">
                    <div v-if="scope.row.$index >= 0">
                        <template v-if="table_config.operation.cols">
                            <div class="btn" v-for="item in table_config.operation.cols.slice(0, 5)" :key="item.label">
                                <el-button @click="item.handleRow(scope.row, item)" plain :type="item.type" size="mini">
                                    {{ item.label }}
                                </el-button>
                            </div>
                        </template>
                        <!-- 操作列超过3个，用更多下拉显示 -->
                        <el-dropdown v-if="isShowOperationCols">
                            <span class="el-dropdown-link">
                                更多<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item v-for="item in table_config.operation.cols.slice(2)" :key="item.label"
                                    @click.native="item.handleRow(scope.row, item.label)">
                                    {{ item.label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </template>
            </el-table-column>
            <el-table-column width="40" v-if="openColumn" :fixed="configFixed.flag">
                <!-- 表头名称和图标 -->
                <template #header="{ column }">
                    <span class="header-icon">
                        <i class="el-icon-setting" @click="dialogVisible = true" :column="column"></i>
                    </span>
                </template>
            </el-table-column>
        </el-table>
        <Draggable title="自定义表单字段" :dialogVisible="dialogVisible" :list="list" :keyName="routerName"
            @getDraggableList="getDraggableList" @closeDialog="closeDialog"></Draggable>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Draggable from '../Draggable';
import elementResize from 'element-resize-detector'
export default {
    components: { Draggable },
    props: {
        //打开设置栏
        openColumn: {
            type: Boolean,
            default: true
        },
        isSelect: {
            type: Boolean,
            default: false
        },
        configFixed: {
            type: Object,
            default: () => {
                return { flag: false }
            }
        },
        config: {
            type: Object,
            default: () => { }
        },
        dataList: {
            type: Array,
            default: () => {
                return []
            }
        },
        loading: {
            type: Boolean,
            default: false
        },
        tableThead: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    data() {
        return {
            // tableThead: [
            //     {
            //         isShow: true, label: '姓名', prop: 'name', minWidth: '150px', router: true, routerPath: 'xxx'
            //     },
            //     {
            //         isShow: true, label: '性别', prop: 'sex', minWidth: '100px', filter: true, callback: (rowData) => {
            //             let data = sexType[rowData.sex]
            //             if (data) {
            //                 return data.label
            //             }
            //         }
            //     },
            //     { isShow: true, label: '头像', prop: 'img', minWidth: '100px', image: true },
            //     { isShow: true, label: '电话', prop: 'phone', minWidth: '150px', },
            //     { isShow: true, label: '时间', prop: 'time', minWidth: '200px', sortable: true },
            //     {
            //         isShow: true, label: '角色', prop: 'role', minWidth: '150px', filter: true, colorName: '',
            //         callback: (rowData) => {
            //             let data = roleType[rowData.role]
            //             if (data) {
            //                 return data.label
            //             }
            //         },
            //         specialClass: (rowData) => {
            //             let data = roleType[rowData.role]
            //             if (data) {
            //                 return data.className
            //             }
            //         }
            //     },
            //     {
            //         isShow: true,
            //         label: '状态',
            //         prop: 'status',
            //         minWidth: '150px',
            //         switch: true,
            //         callback: this.changeStatus
            //     },
            // ],
            showTable: true,
            table_config: {
                isCheckBox: false,    // 是否多选
                isOperation: true,   // 是否有操作列表
                operation: {        // 操作
                    cols: []
                },
            },
            tableDataList: [],
            dialogVisible: false,
            list: JSON.parse(JSON.stringify(this.tableThead)),
            itemList: this.tableThead,
            routerName: this.$route.name + '_table',
            erd: null
        }
    },
    computed: {
        ...mapGetters([
            'codeList'
        ]),
        isShow() {
            return this.table_config.isOperation && this.table_config.operation.cols.length
        },
        isShowOperationCols() {
            let list = this.table_config.operation.cols
            return list.length && list.length > 5
        }
    },
    watch: {
        // 监听传过来的config，进行初始化
        config: {
            handler(newVal) {
                if (newVal) {
                    this.initConfig()
                }
            },
            immediate: true
        },
        dataList: {
            handler(newVal) {
                this.tableDataList = newVal;
                console.log(this.dataList)
                this.setTableHeight(this.dataList);
                setTimeout(() => {
                    this.listenToTable();
                }, 100)
            },
            deep: true
        }
    },
    mounted() {
        this.erd = elementResize();
        this.getList();
        this.listenToTable();
    },
    methods: {
        selectable(row) {
            // console.log('select:', row.$index)
            return row.$index >= 0
        },
        //监听table 高度
        listenToTable() {
            this.erd.listenTo(this.$refs['app-container'], element => {
                this.$nextTick(() => {
                    this.setTableHeight(this.dataList);
                })
            });
        },
        setTableHeight(dataList) {
            let table = document.getElementById('elTable');
            let tableBody = table.querySelectorAll('.el-table__body-wrapper')[0];
            let tableHeight = tableBody.clientHeight;
            // console.log('表格高度：', table, tableBody, tableHeight)
            let tableRowHeight = tableHeight / 10
            this.$nextTick(() => {
                let tableRow = tableBody.querySelectorAll('.el-table__row');
                Array.from(tableRow).forEach(element => {
                    element.style.height = `${tableRowHeight}px`
                });
                this.tableDataList = this.padArray(dataList).map((e, i) => {
                    let objLength = Object.keys(e).length;
                    return { ...e, $index: objLength ? i : -1 }
                })
                // console.log(this.tableDataList)
            })
        },
        padArray(arr, length = 10, padValue = {}) {
            while (arr.length < length) {
                arr.push(padValue);
            }
            return arr;
        },
        closeDialog() {
            this.dialogVisible = false
        },
        getDraggableList(list = this.tableThead) {
            this.itemList = list;
            // console.log(this.itemList)
            this.refreshTable();
        },

        getList() {
            if (sessionStorage.getItem('userType') !== 'ADMIN') {
                let cols = this.table_config.operation.cols
                this.table_config.operation.cols = cols.filter(item => {
                    return this.codeList.indexOf(item.flag) !== -1
                })
            }
            // let hasList = sessionStorage.getItem(this.routerName) || null;
            // if (hasList && JSON.parse(hasList)) {
            //     this.itemList = JSON.parse(hasList)
            // } else {
            //     this.itemList = JSON.parse(JSON.stringify(this.tableThead))
            // }
        },
        //刷新表单；
        refreshTable() {
            this.showTable = false;
            this.$nextTick(() => {
                this.showTable = true;
            })
        },
        // 初始化配置
        initConfig() {
            for (let key in this.config) {
                if (Object.keys(this.table_config).includes(key)) {
                    this.table_config[key] = this.config[key]
                }
            };
            this.getList();
        },
        // 多选事件
        handleSelectionChange(val) {
            this.$emit('selection-change', val)
        },
        // 排序事件
        handleSortChange(val) {
            this.$emit('sort-change', val)
        },
        //点击事件
        handleRowClick(val) {
            this.$emit('row-click', val)
        }
    }
}
</script>

<style scoped>
.btn {
    display: flex;
    justify-content: center;
    display: inline-block;
    margin: 5px 0 0 10px;
}

.btn:first-child {
    margin-left: 0;
}

.color1 {
    color: red;
}

.color2 {
    color: green;
}

.color3 {
    color: blue;
}

.el-dropdown {
    margin-left: 10px;
    cursor: pointer;
}

.header-icon {
    cursor: pointer;
}

::v-deep .table {

    .el-table__fixed,
    .el-table__fixed-left,
    .el-table__fixed-right {
        height: calc(100% - 18px) !important;

        td {
            pointer-events: auto;
        }
    }
}

::v-deep tbody .el-table__cell {
    padding: 0;
}

.app-container {
    height: 100%;


}
</style>